package com.kfm.am.exec;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Exec02 {

    public static void main(String[] args) {
        // 将一个UTF-8编码的文件转换成一个GBK格式的文件，分别使用字节流和字符流实现。
        File f1 = new File("io/csb.txt");
        File f2 = new File("io/csb_gbk.txt");
        File f3 = new File("io/csb_gbk2.txt");
        conversion2(f1, f3, "GBK");
    }

    private static void conversion(File original, File target, String charSet) {
        // 字符流  Reader Writer
        try (FileReader reader = new FileReader(original, StandardCharsets.UTF_8);
             FileWriter writer = new FileWriter(target, Charset.forName(charSet));) {
            char[] chars = new char[1024];
            int read = 0;
            while ((read = reader.read(chars)) != -1) {
                writer.write(chars, 0, read);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }


    }

    private static void conversion2(File original, File target, String charSet) {
        try (FileInputStream in = new FileInputStream(original);
             FileOutputStream out = new FileOutputStream(target);) {
            byte[] bytes = in.readAllBytes();
            String str = new String(bytes); // 用UTF-8格式的字符串
            byte[] bytes1 = str.getBytes(charSet);
            out.write(bytes1);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
